package com.onenine.app.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;

import com.alibaba.sdk.android.manager.OssManager;
import com.cjt2325.cameralibrary.util.FileUtil;
import com.onenine.app.R;
import com.onenine.app.event.VideoFinishEvent;
import com.onenine.app.utils.VideoFilter;
import com.onenine.app.view.popwin.MediaPopWindow;
import com.onenine.base.base.BaseActivity;
import com.onenine.base.utils.AppConfig;
import com.onenine.base.utils.Toasty;
import com.onenine.common.fileprovider.FileProvider7;
import com.onenine.common.util.ActivityUtils;
import com.onenine.common.util.Logger;
import com.onenine.common.util.SizeUtils;
import com.onenine.common.util.TimeUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * 创建时间：2018/8/24 0024 12:16
 * 创建人：fly
 * 功能描述：带相册上传功能的Activity
 */
public abstract class UploadImageActivity extends BaseActivity implements
        MediaPopWindow.OnTakePictureCallback, EasyPermissions.PermissionCallbacks, OssManager.Callback {

    public static final String IMAGE_ADD = "image/add";
    private static final String[] CAMERA_PERMISSIONS = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
    protected static final int REQ_OPEN_CAMERA = 189;
    protected static final int REQ_OPEN_ALBUM = REQ_OPEN_CAMERA + 1;
    private String mCurrentPhotoPath;
    private int mMediaType, mCompressCount, mCompressPosition;
    protected List<String> mImagePaths = new ArrayList<>();

    /**
     * 打开相机
     */
    private void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            String filename = TimeUtils.getNowMills() + ".png";
            File file = new File(Environment.getExternalStorageDirectory(), filename);
            mCurrentPhotoPath = file.getAbsolutePath();
            Uri fileUri = FileProvider7.getUriForFile(this, file);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
            startActivityForResult(takePictureIntent, 100);
        } else {
            Toasty.showNormal(R.string.can_not_open_camera);
        }
    }

    /**
     * 准备加载相机
     */
    protected void launchCamera() {
        if (mImagePaths.size() >= getMaxImageCount() + 1) {
            Toasty.showNormal("最多只能传" + getMaxImageCount() + "张相片");
            return;
        }
        openCamera();
    }

    /**
     * 准备加载视频录制
     */
    protected void launchVideoCamera() {
        ActivityUtils.startActivity(this, VideoRecorderActivity.class);
    }

    @Override
    public void onCamera(int mediaType) {
        mMediaType = mediaType;
        if (EasyPermissions.hasPermissions(this, CAMERA_PERMISSIONS)) {
            if (mediaType == MediaPopWindow.IMAGE_TYPE) {
                launchCamera();
            } else if (mediaType == MediaPopWindow.VIDEO_TYPE) {
                launchVideoCamera();
            }
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.permission_camera_hint)
                    , REQ_OPEN_CAMERA, CAMERA_PERMISSIONS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onSelectPicture(int mediaType) {
        mMediaType = mediaType;
        if (EasyPermissions.hasPermissions(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
            if (mediaType == MediaPopWindow.IMAGE_TYPE) {
                launchAlbum();
            } else if (mediaType == MediaPopWindow.VIDEO_TYPE) {
                launchVideoAlbum();
            }
        } else {
            EasyPermissions.requestPermissions(this, getString(R.string.permission_extra_storage_hint), REQ_OPEN_ALBUM, Manifest.permission.READ_EXTERNAL_STORAGE);
        }
    }

    /**
     * 准备加载相册
     */
    protected void launchAlbum() {
        if (mImagePaths.size() >= getMaxImageCount() + 1) {
            Toasty.showNormal(getString(R.string.album_max_count_limit_hint, getMaxImageCount()));
            return;
        }
        int size = AppConfig.SCREEN_WIDTH / 3 - SizeUtils.dp2px(10);
        int pSize = mImagePaths.size();
        Matisse.from(this)
                .choose(MimeType.ofImage())//显示照片
                .countable(false)//无序选择图片
                .showSingleMediaType(true)//只显示一种媒体类型，此处只会显示图片，过滤了视频
                .maxSelectable(pSize == 0 ? getMaxImageCount() : getMaxImageCount() - pSize + 1)//最大选择数量为9
                .gridExpectedSize(size)//图片显示表格的大小getResources()
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(101);//请求码
    }

    /**
     * 加载视频相册,只能选一个视频
     */
    protected void launchVideoAlbum() {
        Matisse.from(this)
                .choose(MimeType.ofVideo())//显示照片
                .countable(false)//无序选择图片
                .showSingleMediaType(true)//只显示一种媒体类型
                .maxSelectable(1)//最大选择数量为1
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)//图像选择和预览活动所需的方向。
                .addFilter(new VideoFilter())
                .thumbnailScale(0.85f)//缩放比例
                .theme(R.style.Matisse_Light)//主题
                .imageEngine(new GlideEngine())//加载方式
                .forResult(102);//请求码
    }

    /**
     * 压缩图片在100kb左右
     *
     * @param images
     */
    private void compressImages(List<String> images) {
        mCompressCount = images.size();
        mCompressPosition = 0;
        Luban.with(this)
                .load(images).ignoreBy(100)
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onSuccess(File file) {
                        mCompressPosition++;
                        mImagePaths.add(0, file.getPath());
                        compressImageSuccess(file);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                List<String> retList = Arrays.asList(mCurrentPhotoPath);
                compressImages(retList);
            } else if (requestCode == 101) {
                if (!mImagePaths.contains(IMAGE_ADD)) {
                    mImagePaths.add(IMAGE_ADD);
                }
                compressImages(Matisse.obtainPathResult(data));
            } else if (requestCode == 102) {
                //todo 后期要做压缩
                List<String> retList = Matisse.obtainPathResult(data);
                if (!retList.isEmpty()) {
                    String videoPath = retList.get(0);
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    retriever.setDataSource(videoPath);
                    Bitmap frameBitmap = retriever.getFrameAtTime();
                    if (frameBitmap != null) {
                        String framePath = FileUtil.saveBitmap(AppConfig.VIDEO_CAMERA_DIR, frameBitmap);
                        finishSelectVideo(new VideoFinishEvent(videoPath, framePath));
                        frameBitmap.recycle();
                    }
                }
            }
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == REQ_OPEN_CAMERA && CAMERA_PERMISSIONS.length == perms.size()) {
            if (mMediaType == MediaPopWindow.IMAGE_TYPE) {
                launchCamera();
            } else if (mMediaType == MediaPopWindow.VIDEO_TYPE) {
                launchVideoCamera();
            }
        } else if (requestCode == REQ_OPEN_ALBUM) {
            if (mMediaType == MediaPopWindow.IMAGE_TYPE) {
                launchAlbum();
            } else if (mMediaType == MediaPopWindow.VIDEO_TYPE) {
                launchVideoAlbum();
            }
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(getString(R.string.permission_apply))
                    .setRationale(getString(R.string.permission_refuse_always_hint)).build().show();
        } else if (requestCode == REQ_OPEN_CAMERA) {
            Toasty.showNormal(R.string.permission_camera_hint);
        } else if (requestCode == REQ_OPEN_ALBUM) {
            Toasty.showNormal(R.string.permission_extra_storage_hint);
        }
    }

    @Override
    public void onSuccess(String url) {
        uploadImagesSuccess(url);
    }

    @Override
    public void onProgress(float progress) {

    }

    @Override
    public void onFailure(int errorCode, String errorMsg) {
        dismissLoading();
        Logger.e("上传失败：" + errorCode + "," + errorMsg);
    }

    /**
     * 是否压缩完毕
     *
     * @return
     */
    protected boolean isImageCompressed() {
        return mCompressPosition >= mCompressCount;
    }

    /**
     * 最大图片数量
     *
     * @return
     */
    protected int getMaxImageCount() {
        return AppConfig.IMAGE_MAX_DEFAULT;
    }

    /**
     * 压缩每张后
     */
    protected abstract void compressImageSuccess(File file);

    /**
     * 完成视频选择
     */
    protected void finishSelectVideo(VideoFinishEvent event) {

    }

    /**
     * 图片全部上传完成
     *
     * @param imageUrls
     */
    protected abstract void uploadImagesSuccess(String imageUrls);

    @Override
    public void onDestroy() {
        super.onDestroy();
        mImagePaths.clear();
    }

}
